package io;

import java.io.*;
import java.nio.charset.StandardCharsets;

/*
  向文件中写入文本数据
 */
public class WriteStringDemo {
    public static void main(String[] args) throws IOException {
        //向文件fos.txt中写入字符串
        FileOutputStream fos = new FileOutputStream("fos.txt",true);//true说明是追加模式，不会清除原来的数据，false则在运行时会先清除原来数据
        File file = new File("fos.txt");
        FileInputStream fis = new FileInputStream(file);
        //String line = "爱你孤身走暗巷";
        /*
           String 提供的方法:
           byte[] getBytes(Charset charset)
         */
        String  line = "爱你~";
        byte[] data = line.getBytes(StandardCharsets.UTF_8);
        fos.write(data);
        line = "如果你突然打了个喷嚏，啊~那一定是我在想你\n";
        data = line.getBytes(StandardCharsets.UTF_8);
        fos.write(data);
        System.out.println("写出完毕！");

        byte[] datas = new byte[(int) file.length()];
        fis.read(datas);
        String str = new String(datas,StandardCharsets.UTF_8);
        System.out.println("读取的数据为:"+str);
        fos.close();
        fis.close();
    }
}
